package com.yzkj.siot.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yzkj.siot.exp.BizExp;
import com.yzkj.siot.uesr.dto.CurrentUser;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenHelper {

    // 设置过期时间
    private static final long EXPIRE_DATE = 60 * 60 * 24 * 7 * 1000;

    // token秘钥
    private static final String TOKEN_SECRET = "yzkj-token-2021-1024";


    public static String create(Integer userId, Integer tenantId, Integer roleId, Integer userType, String userEamil) {
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带用户信息，生成签名
            return JWT.create()
                    .withHeader(header)
                    .withClaim("userId", userId)
                    .withClaim("tenantId", tenantId)
                    .withClaim("roleId", roleId)
                    .withClaim("userType", userType)
                    .withClaim("userEmail", userEamil)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            throw new BizExp("生成token时出现错误");
        }
    }

    public static CurrentUser getCurrentUser(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            CurrentUser currentUser = new CurrentUser();

            currentUser.setUserType(jwt.getClaim("userType").asInt());

            if (currentUser.getUserType() == 3) {
                currentUser.setTenantId(jwt.getClaim("tenantId").asInt());
            }
            if (currentUser.getUserType() == 2 || currentUser.getUserType() == 1) {
                currentUser.setUserId(jwt.getClaim("userId").asInt());
                if (currentUser.getUserType() == 2) {
                    currentUser.setRoleId(jwt.getClaim("roleId").asInt());
                    currentUser.setTenantId(jwt.getClaim("tenantId").asInt());
                    currentUser.setUserEmail(jwt.getClaim("userEmail").asString());
                }
            }

            return currentUser;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizExp("token验证失败！");
        }
    }

    public static Integer verify(String token, String claim) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim(claim).asInt();
        } catch (Exception e) {
            throw new BizExp("token验证失败！");
        }
    }

    /**
     * 验证token，通过返回管理员Id
     *
     * @param token token字符串
     * @return 管理员Id
     **/
    public static Integer verify(String token) {

        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("adminId").asInt();
        } catch (Exception e) {
            throw new BizExp("token验证失败！");
        }
    }
}
